package com.ocelot.san.controller;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.servlet.ServletContext;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.ocelot.san.constants.ApplicationConstants;

@ManagedBean(name = "loginController")
@ViewScoped
public class LoginController {

	private Log log = LogFactory.getLog(LoginController.class);

	private String userId;
	private String password;

	private Authentication createAuthenticationToken() {
		UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(
				getUserId(), getPassword());
		return usernamePasswordAuthenticationToken;
	}

	/**
	 * This action logs the user in and returns to the secure area.
	 * 
	 * @return String path to secure area
	 */
	public String login() {
		AuthenticationManager authenticationManager = (AuthenticationManager) getSpringBean(ApplicationConstants.AUTH_MANAGER);
		Authentication authenticationRequestToken = createAuthenticationToken();
		try {
			Authentication authenticationResponseToken = authenticationManager
					.authenticate(authenticationRequestToken);
			SecurityContextHolder.getContext().setAuthentication(
					authenticationResponseToken);
			if (authenticationResponseToken.isAuthenticated()) {
				return "home.xhtml";
			}
		} catch (BadCredentialsException badCredentialsException) {
			FacesMessage facesMessage = new FacesMessage(
					"Acceso inválido: verifica tu usuario/password e intenta de nuevo.");
			FacesContext.getCurrentInstance().addMessage(null, facesMessage);
			log.debug(badCredentialsException);
		} catch (LockedException lockedException) {
			FacesMessage facesMessage =
			new FacesMessage("Cuenta Bloqueada: contacta con tu administrador.");
			FacesContext.getCurrentInstance().addMessage(null, facesMessage);
			log.debug(lockedException);
		} catch (DisabledException disabledException) {
			FacesMessage facesMessage = new FacesMessage(
					"Cuenta Desactivada: contacta con tu administrador.");

			FacesContext.getCurrentInstance().addMessage(null, facesMessage);
			log.debug(disabledException);
		}

		return null;
	}

	private Object getSpringBean(String name) {
		WebApplicationContext ctx = WebApplicationContextUtils
				.getRequiredWebApplicationContext((ServletContext) FacesContext
						.getCurrentInstance().getExternalContext().getContext());
		return ctx.getBean(name);
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getUserId() {
		return userId;
	}

	public void setUserId(String userId) {
		this.userId = userId;
	}

}
